package com.deer.wms.ASN.manage.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.ASN.manage.dao.AsnDetailMapper;
import com.deer.wms.ASN.manage.model.asn.AsnDetail;
import com.deer.wms.ASN.manage.model.asn.AsnDetailCriteria;
import com.deer.wms.ASN.manage.model.asn.AsnDetailDto;
import com.deer.wms.ASN.manage.model.asn.AsnMaster;
import com.deer.wms.ASN.manage.service.AsnDetailService;
import com.deer.wms.ASN.manage.service.AsnMasterService;
import com.deer.wms.base.system.model.PurchaseOrderBO;
import com.deer.wms.base.system.model.PurchaseOrderDetailBO;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.ware.task.constant.WareTaskConstant;
import com.deer.wms.ware.task.model.SO.SoDetail;
import com.deer.wms.ware.task.model.Wave.WaveDetail;
import com.deer.wms.ware.task.model.pickTask.PickTask;
import com.deer.wms.ware.task.model.pickTask.PickTaskCriteria;
import com.deer.wms.ware.task.service.impl.PushErpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *
 * @author guo
 * @since 2020/01/03
 */
@Service
@Transactional
public class AsnDetailServiceImpl extends SuperServiceImpl<AsnDetailMapper, AsnDetail> implements AsnDetailService {

    @Autowired
    private AsnDetailMapper asnDetailMapper;
    @Autowired
    private AsnMasterService asnMasterService;
    @Autowired
    private PushErpServiceImpl pushErpService;

    @Override
    public List<AsnDetailDto> findList(AsnDetailCriteria criteria) {
        return asnDetailMapper.findList(criteria);
    }

    @Override
    public void deleteByBillNo(String billNo){
        asnDetailMapper.deleteByBillNo(billNo);
    }

    @Override
    public List<AsnDetail>findByBillNo(String billNo){
        return asnDetailMapper.findByBillNo(billNo);

    }

    @Override
    public List<AsnDetailDto> findByDetailNo(String detailNo){
        return asnDetailMapper.findByDetailNo(detailNo);

    }

    @Override
    public AsnDetail findBy(String field, String value) {
        QueryWrapper<AsnDetail> qw = new QueryWrapper<>();
        return getOne(qw.eq(field, value));
    }

    @Override
    public List<AsnDetailDto> findQcList(AsnDetailCriteria criteria) {
        return asnDetailMapper.findQcList(criteria);
    }

    /**
     * 同步拉取
     *  @param map
     * @param asnMasterMap
     * @param billNos
     */
    @Override
    public void savePurchaseOrder(Map<String, Object> map, Map<String, AsnMaster> asnMasterMap, List<String> billNos) {
        List<AsnDetail> newAsnDetail = new ArrayList<>();
        List<PurchaseOrderBO> purchaseOrderBOS = pushErpService.GetAllIMInSourceBills(map);
        for (PurchaseOrderBO bo : purchaseOrderBOS) {
            String billNo = bo.getBillNo();
            AsnMaster asnMaster = asnMasterMap.get(billNo);
            asnMaster.setBillNo(bo.getBillNo());
            asnMaster.setSupplierId(bo.getSupplierId());//供应商ID
            asnMaster.setSupplierName(bo.getSupplierName());//供应商名称
            asnMaster.setBeforeNum(bo.getId());
            asnMaster.setCreateUserId(bo.getCustomerId());//客户ID
            asnMaster.setAsnUdfHs2(bo.getCustomerName());//客户名称
            asnMaster.setDeptId(bo.getDeptId());//部门ID
            asnMaster.setUda3(bo.getDeptName());//部门名称
            asnMaster.setMemo(bo.getRemark());//备注
            asnMaster.setAgreementNo(bo.getDetails().iterator().next().getAgreementNo()); //履约号
            asnMaster.setAsnType(bo.getDetails().iterator().next().getTargetBillTypeId());
            asnMasterService.updateById(asnMaster);
            Integer i = 1;
            for (PurchaseOrderDetailBO purchaseOrderDetailBO : bo.getDetails()) {
                AsnDetail asnDetail = new AsnDetail();
                asnDetail.setBillNo(asnMaster.getBillNo());//ASN单号
                asnDetail.setPackDetailId(33469);//基本单位ID
                asnDetail.setPackDescribe(purchaseOrderDetailBO.getUnitName());//单位
                asnDetail.setExpectPackDetailId(purchaseOrderDetailBO.getItemId());//物料ID
                asnDetail.setItemCode(purchaseOrderDetailBO.getItemNumber());//物料编码
                asnDetail.setItemName(purchaseOrderDetailBO.getItemName());//物料名称
                asnDetail.setSourceId(bo.getId());
                asnDetail.setUda1(purchaseOrderDetailBO.getItemModel());//规格型号
                asnDetail.setAcceptPackDetailId(purchaseOrderDetailBO.getAuxPropClassId());//辅助属性类别ID
                asnDetail.setUpperPackDetailId(purchaseOrderDetailBO.getAuxPropId());//辅助属性ID
                asnDetail.setAsnUdfDs1(purchaseOrderDetailBO.getAuxPropName());//辅助属性
                asnDetail.setDetailNo(asnMaster.getBillNo() + "-" + i);
                asnDetail.setStockId(purchaseOrderDetailBO.getStockId());  //仓库id
                asnDetail.setStockName(purchaseOrderDetailBO.getStockName()); //仓库名称
                asnDetail.setMemo(purchaseOrderDetailBO.getRemark());
                asnDetail.setErpBatch(purchaseOrderDetailBO.getBatchNo());//批号
                asnDetail.setRowIndex(purchaseOrderDetailBO.getRowIndex());//行号
                asnDetail.setPackCode(purchaseOrderDetailBO.getMtoNo());//计划跟踪号
                asnDetail.setExpectQuantity(purchaseOrderDetailBO.getOriginQty());
                i++;
                newAsnDetail.add(asnDetail);
            }
        }
        List<AsnDetail> allAsnDetails = new ArrayList<>();
        List<AsnDetail> oldAsnDetails = list(new QueryWrapper<AsnDetail>().in("bill_no", billNos));

        if (ObjectUtil.isEmpty(oldAsnDetails)) {
            oldAsnDetails = new ArrayList<AsnDetail>();
        }
        if (ObjectUtil.isEmpty(newAsnDetail)) {
            newAsnDetail = new ArrayList<AsnDetail>();
        }
        allAsnDetails.addAll(oldAsnDetails);
        allAsnDetails.addAll(newAsnDetail);
        //行号可能重复，不能作为唯一条件去重
        Map<AsnDetail, AsnDetail> newMap = newAsnDetail.stream()
                .collect(Collectors.toMap(item -> item, asnDetail -> asnDetail, (oldValue, newValue) -> newValue));
        //新单子老单子合并
        Map<AsnDetail, AsnDetail> oldMap = oldAsnDetails.stream()
                .collect(Collectors.toMap(item -> item, asnDetail -> asnDetail, (oldValue, newValue) -> newValue));
        //同步拉取
        contrastSoDetail(allAsnDetails, newMap, oldMap);
    }

    public void contrastSoDetail(List<AsnDetail> allAsnDetails, Map<AsnDetail, AsnDetail> newMap, Map<AsnDetail, AsnDetail> oldMap) {
        for (AsnDetail key : allAsnDetails) {
            AsnDetail newSd = newMap.get(key);
            AsnDetail oldSd = oldMap.get(key);

            if (newSd == null) {
                if (oldSd.getAcceptQuantity() > 0) {
                    continue;
                }
                //如果老单子删除
                removeById(oldSd.getId());
            } else if (ObjectUtil.isEmpty(oldSd)) {
                //如果老单子为空则新增一条
                newSd.setState(0);
                this.save(newSd);
            } else {
                //同步仓库
                oldSd.setStockId(newSd.getStockId());
                //都有，则判断数量，有变化则修改
                if (ObjectUtil.notEqual(oldSd.getExpectQuantity(), newSd.getExpectQuantity())) {
                    oldSd.setExpectQuantity(newSd.getExpectQuantity());
                }
                this.updateById(oldSd);
            }
        }
        }
    }

